/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package am.aua.renju.web;

import am.aua.renju.web.filldata.Data;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Ara Yeritsian
 */
public class TemplateRender {

    private Configuration cfg;

    public TemplateRender(ServletContext servletContext, String path) {
        cfg = new Configuration();
        cfg.setServletContextForTemplateLoading(servletContext, path);
    }

    public void render(HttpServletResponse response, Data view) throws ServletException, IOException {
        Template t = cfg.getTemplate(view.fileName);
        response.setContentType("text/html; charset=" + t.getEncoding());
        Writer out = response.getWriter();
        try {
            t.process(view.fillData, out);
        } catch (TemplateException e) {
            throw new ServletException(
                    "Error while processing FreeMarker template", e);
        }
    }

    public void ajaxRender(HttpServletResponse response, String jsonData) throws IOException {
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.getWriter().write(jsonData);
    }
}
